<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button size="small" type="primary" @click="visible =  true">
          添加
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="small"
        highlight-current-row
      >
        <el-table-column
          prop="id"
          label="id"
          min-width="50"
        />
        <el-table-column
          prop="region_name"
          label="代理区域"
          min-width="50"
        />

        <el-table-column
          prop="share_ratio"
          label="分红比例(%)"
          min-width="150"
        >
          <template  slot-scope="scope">
            <div style="cursor:pointer" @click="open(scope.row.id,scope.row.share_ratio)">
              {{scope.row.share_ratio}}
              <i class="el-icon-edit"></i>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="region_name"
          label="用户"
          min-width="50"
        >

            <template slot-scope="scope" v-if="scope.row.user">
              <span>{{scope.row.user.nickname}}</span>
              <img :src="scope.row.user.avatar" style="width: 35px;height: 35px">
            </template>

        </el-table-column>
        <el-table-column
          prop="address"
          label="地区"
          min-width="150"
        />

        <el-table-column
          prop="createtime"
          label="时间"
          min-width="150"
        />
        <el-table-column label="操作" min-width="100" fixed="right" align="center">
          <template slot-scope="scope">

            <el-button type="text" size="small"
                       @click="delAreas( scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <el-dialog title="设定区域代理"
               :visible.sync="visible"
               width="700px"

               :before-close="handleClosePic"
               class="dia">

        <el-form>

          <el-form-item label="搜索用户：" prop="content">
            <div style="display: flex">
              <el-input placeholder="请输入uid或手机号" v-model="nickname">
              </el-input>
              <el-button
                type="primary"
                class="ml50"
                @click="search"
              >搜索</el-button>
            </div>
          </el-form-item>
          <el-form-item label="绑定的用户：" prop="content" v-if="addressform.user_id > 0">
            <el-input placeholder="请输入姓名昵称手机号" v-model="addressform.user_id" disabled></el-input>
            <div>
              <div>{{ user_nickname }}</div>
              <img :src="user_avatar" style="width: 50px;height: 50px;border-radius: 50%">
            </div>
          </el-form-item>

        <div style="display: flex">

          <el-form-item prop="province" style="margin-right:10px">
            <el-select v-model="addressform.province" placeholder="请选择省" size="small" filterable
                       @change="addressSelect(addressform.province,2)">
              <el-option v-for="item in provinceOptions" :key="item.id" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="city" style="margin-right:10px">
            <el-select v-model="addressform.city" placeholder="请选择市" size="small" filterable
                       @change="addressSelect(addressform.city,3)">
              <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="county" style="margin-right:10px">
            <el-select v-model="addressform.county" placeholder="请选择区" size="small" filterable
                       @change="addressSelect(addressform.county,4)">
              <el-option v-for="item in districtOptions" :key="item.id" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>


        </div>

          <el-form-item  label="分成比例：" prop="content">
            <el-input placeholder="请输入分成比例" v-model="addressform.share_ratio"></el-input>
          </el-form-item>

          <el-form-item label="代理级别：">
            <el-radio-group v-model="addressform.type">
              <el-radio :label="0">省代</el-radio>
              <el-radio :label="1">市代</el-radio>
              <el-radio :label="2">区代</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <div class="acea-row row-center">
              <el-button
                type="primary"
                class="ml50"
                @click="submenus"
              >提交</el-button>
            </div>
          </el-form-item>
        </el-form>
    </el-dialog>
  </div>
</template>

<script>

import {
  cityDataLst
} from "@/api/system";
import {
  nickname_uid,
  getAreaList,
  delArea,
  addArea,
  updateShareRatio
} from "@/api/user";
import Template from "@/views/app/wechat/wxTemplate/index.vue";

export default {
  name: 'UserGroup',
  components: {Template},
  data() {
    return {
      visible: false,
      tableFrom: {
        page: 1,
        limit: 20
      },
      tableData: {
        data: [],
        total: 0
      },
      listLoading: true,
      provinceOptions: [],
      cityOptions: [],
      districtOptions: [],
      addressform: {
        province: '',
        city: '',
        county: '',
        street: '',
        user_id:0,
        share_ratio:'',
        type:'0'
      },
      user_nickname: '',
      user_avatar: '',
      nickname: '',
      user_uid: 0
    }
  },
  mounted() {
    this.getCitys(0)
    this.getList()
  },
  methods: {
    open(id,share_ratio){
        let that = this
        this.$prompt('当前比例：' + share_ratio + '%', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
          updateShareRatio({id:id,share_ratio:value}).then(result => {
            that.$message.success(result.message)
            that.getList()
          })
      }).catch(() => {

      });
    },
    delAreas(id){
        let that = this
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delArea({
          id: id
        }).then(result => {
          that.$message.success(result.message)
          that.getList()
        }).catch(error => {
          that.$message.error('删除失败')
        })
      })

    },
    search(){
      nickname_uid({
        nickname:this.nickname
      }).then(result => {

            this.addressform.user_id = result.data.uid
            this.user_nickname = result.data.nickname
            this.user_avatar = result.data.avatar
          console.log(this.addressform.user_id)
          this.$forceUpdate()

      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    getList(){
      getAreaList({
        page: this.tableFrom.page,
        limit: this.tableFrom.limit,
      }).then(result => {
          this.tableData.data = result.data.data
          this.tableData.total = result.data.total
      })
    },
    submenus() {
      let that = this
      //判定
      if(!that.addressform.province){
        this.$message.error('请选择省')
        return false
      }
      if(that.addressform.type > 0) {
        if (!that.addressform.city) {
          this.$message.error('请选择市')
          return false
        }
      }
      if(that.addressform.type == 2) {
        if (!that.addressform.county) {
          this.$message.error('请选择区')
          return false
        }
      }

      if(!that.addressform.user_id){
        this.$message.error('请选择用户')
        return false
      }

      if(!that.addressform.share_ratio){
        this.$message.error('请输入分成比例')
        return false
      }

      //请求添加
      addArea(that.addressform).then(result => {
            this.visible = false
            this.$message.success('添加成功')
            this.getList()

      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    handleClosePic() {
      this.visible = false
    },
    // 列表
    //地区下拉框选择事件
    addressSelect(data, index) {
      let addressCode = ''
      //选择任意下拉框需把下一个下拉框清空再获取
      switch (index) {
        case 2:
          this.cityOptions = []
          this.districtOptions = []
          this.townOptions = []
          this.addressform.city = ''
          this.addressform.county = ''
          this.addressform.street = ''
          addressCode = this.provinceOptions.find(a => a.name == data).id//获取code调接口获取下一级 下方同理
          break;
        case 3:
          this.districtOptions = []
          this.townOptions = []
          this.addressform.county = ''
          this.addressform.street = ''
          addressCode = this.cityOptions.find(a => a.name == data).id
          break;
        case 4:
          this.townOptions = []
          this.addressform.street = ''
          addressCode = this.districtOptions.find(a => a.name == data).id
          break;
        default:
          break;
      }
      if (index == 5) { //此需求是省市区需要中文汉字(name)传给后台，街道需要代码(code)
        this.addressform.addressCode = this.townOptions.find(a => a.name == data).id
        return
      }
      this.getCitys(addressCode, index)
    },
//获取地区下拉框方法
    getCitys(code = '', level = 1) {
      console.log('执行啊执行')
      cityDataLst(code).then(result => {
        this.listLoading = false
        let res = result.data
        switch (level) {
          case 1:
            this.provinceOptions = res
            break;
          case 2:
            this.cityOptions = res
            break;
          case 3:
            this.districtOptions = res
            break;
          case 4:
            this.townOptions = res
            break;
          default:
            break;
        }
      })
    },
    pageChange(page) {
      this.tableFrom.page = page
      this.getList()
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val
      this.getList()
    },
    // 添加
    onAdd() {
      this.$modalForm(this.$route.path.indexOf('group') !== -1 ? groupFormApi() : labelFormApi()).then(() => this.getList())
    },
    // 编辑
    onEdit(id) {
      this.$modalForm(this.$route.path.indexOf('group') !== -1 ? groupEditApi(id) : labelEditApi(id)).then(() => this.getList())
    },
    // 删除
    handleDelete(id, idx) {
      this.$modalSure(this.$route.path.indexOf('group') !== -1 ? '删除该分组' : '删除该标签').then(() => {
        this.$route.path.indexOf('group') !== -1 ? groupDeleteApi(id).then(({message}) => {
          this.$message.success(message)
          this.tableData.data.splice(idx, 1)
          this.getList()
        }).catch(({message}) => {
          this.$message.error(message)
        }) : labelDeleteApi(id).then(({message}) => {
          this.$message.success(message)
          this.tableData.data.splice(idx, 1)
        }).catch(({message}) => {
          this.$message.error(message)
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
